
<template>
  <div :class="globalClass" :style="tableStyle">
    <vxe-grid
      :id="`xGrid${tableId}`"
      ref="xGrid"
      class="sortable-column"
      :row-class-name="tableRowClassName"
      :cell-class-name="cellClassName"
      :header-cell-style="headerCellStyle"
      :cell-style="cellStyle"
      column-key
      :row-id="rowId"
      resizable
      :auto-resize="true"
      :height="height"
      :max-height="innerMaxHeight"
      :min-height="innerMinHeight"
      :size="size"
      :show-header-overflow="showHeaderOverflow"
      :loading="loading"
      :show-overflow="showOverflow"
      :show-footer-overflow="showFooterOverflow"
      align="left"
      :header-cell-class-name="headerFilter ? 'header-column-filter' : ''"
      :keep-source="keepSource"
      :column-config="{
        isHover: true, //当鼠标移到列头时，是否要高亮当前列头
        isCurrent: true, //当鼠标点击列头时，是否要高亮当前列
        minWidth: columnMinWidth, //每一列的最小宽度
        resizable: resizable,
        useKey: true,
        drag: true,
        autoOptions: {
          isCalcHeader: true, // 不自适应计算列头宽度
          isCalcBody: true,
          isCalcFooter: true,
        },
      }"
      :keyboard-config="{
        arrowCursorLock: true,
        isClip: true,
        isArrow: true,
        isShift: true,
        isTab: true,
        isEnter: true,
        isEdit: true,
        isBack: true,
        isDel: true,
        isEsc: true,
        isFNR: true,
      }"
      :toolbar-config="{
        custom: customStorage,
        enabled: showToolbar,
      }"
      :tooltip-config="tooltipConfig"
      :footerAlign="footerAlign"
      :custom-config="{
        storage: false, // 是否启用 localStorage 本地保存
      }"
      :checkbox-config="
        Object.keys(checkboxConfig).length
          ? checkboxConfig
          : {
              labelField: labelField, //复选框显示的字段名
              reserve: true, //是否保留勾选状态
              range: !innerTreeConfig, //开启复选框范围选择功能
              checkMethod: myCheckboxMethod,
              highlight: true,
              checkStrictly: checkStrictly,
              isShiftKey: true,
            }
      "
      :seq-config="{
        seqMethod: ({ rowIndex }) =>
          page.currentPage
            ? (page.currentPage - 1) * page.pageSize + rowIndex + 1
            : rowIndex + 1, // 设置序号的起始值
      }"
      :scroll-y="{
        enabled: true, // 默认是false，需要手动设置为true
      }"
      :scroll-x="{ enabled: false, gt: -1 }"
      :tree-config="innerTreeConfig"
      :filter-config="filterConfig"
      :show-footer="showFooter"
      :row-config="{
        isCurrent: !!tableRowClassName, // 当鼠标点击行时，是否要高亮当前行
        isHover: !!tableRowClassName, // 当鼠标移到行时，是否要高亮当前行
        keyField: keyField,
        useKey: true,
        drag: dragRow,
      }"
      :row-drag-config="{
        isCrossTableDrag: isCrossTableDrag,
        dragEndMethod: dragEndMethod,
      }"
      :valid-config="{
        autoPos: false,
        autoClear: false,
      }"
      :edit-config="{
        autoClear: changeEditNeedTrigger ? false : true, // autoClear:true,会导致BaseDateTimePicker，datetime类型控件无法选中时分问题
        afterEditMethod: changeEditNeedTrigger ? afterEditMethod : undefined,
        ...editConfig,
        showIcon: false,
      }"
      :edit-rules="langRule"
      :columns="headerColumns"
      :data="dataSource"
      :show-header="showHeader"
      :footer-method="footerMethod"
      :footer-cell-class-name="footerCellClassName"
      @radio-change="radioChange"
      @checkbox-change="checkboxChange"
      @checkbox-all="checkboxAll"
      @header-cell-click="handleHeaderCellClick"
      @edit-activated="editActivated"
      @cell-dblclick="cellDblclick"
      @cell-click="cellClick"
      @toolbar-tool-click="toolbarToolClick"
      @custom="toolbarToolClick"
      @keydown="handleKeydown"
      @edit-closed="handleEditClosed"
      @column-dragend="handColumnDragend"
      @checkbox-range-select="checkboxRangeSelect"
      @row-insert-dragend="rowInsertDragend"
    >
      <template #pager>
        <vxe-pager
          v-if="Object.keys(page).length"
          :layouts="[
            'Sizes',
            'PrevJump',
            'PrevPage',
            'Number',
            'NextPage',
            'NextJump',
            'FullJump',
            'Total',
          ]"
          v-model:current-page="page.currentPage"
          v-model:page-size="page.pageSize"
          :page-sizes="[10, 50, 100, 200, 300, 500, 1000]"
          :total="page.total"
          @page-change="handlePageChange"
        />
      </template>
      <!-- 表头序号 -->
      <template #seq_header>
        <div
          style="cursor: pointer"
          @click="showHeaderFilter = !showHeaderFilter"
        >
          <i class="vxe-icon--funnel"></i>
        </div>
      </template>
      <!-- 表头筛选列 -->
      <template #filter_header="{ column }">
        <div class="filter-header-title">{{ column.title }}</div>
        <div
          v-for="(option, index) in column.filters"
          :key="index"
          class="filter-header-label"
        >
          <!-- input -->
          <el-input
            v-if="column.params?.filterType === 'label_input'"
            v-model="option.data"
            type="text"
            :placeholder="$t('请输入')"
            clearable
            @input="filterEvent(option)"
          />
          <!-- date -->
          <el-date-picker
            v-if="column.params?.filterType === 'label_date'"
            v-model="option.data"
            type="daterange"
            range-separator="~"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
          <!-- select -->
          <el-select
            v-if="column.params?.filterType === 'label_select'"
            v-model="option.data"
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="op in column.params?.options ?? []"
              :key="op.value"
              :label="$t(op.label)"
              :value="op.value"
            />
          </el-select>
        </div>
      </template>
      <!-- 模糊查询（调用后端接口选择内容） -->
      <template #remoteSelect_edit="{ row, column, rowIndex }">
        <ErrorTooltip :validErrors="validErrors" :field="column.field">
          <RemoteSelect
            :rowIndex="rowIndex"
            :params="column.params?.params"
            :names="row[column.field]"
            :multiple="column.params?.multiple"
            :api-module="column.params?.apiModule"
            :optionClick="column.params?.optionClick"
            :handleOptionChange="column.params?.handleOptionChange"
            :disabled="column.params?.disabled"
            :preset="column.params?.preset"
            :prop="column.field"
            :prop-label="column.params?.propLabel"
            :form-data="row"
            @handle-click="column.params?.handleClick?.(column)"
            @handle-remote-change="
              (val, data) => {
                handleRemoteChange(val, data, column, row, rowIndex);
                row[column.field] = val;
              }
            "
            @handleClear="
              () => {
                onClear(column, row);
              }
            "
          />
        </ErrorTooltip>
      </template>
      <!-- 表头必填 -->
      <template #header="{ column }">
        <!--不必填-->
        <span v-if="!column.params?.require" class="filter-header-title">
          <el-icon :size="14" v-if="column.editRender && editConfig?.enabled">
            <Edit />
          </el-icon>
          {{ column.title }}
        </span>
        <!--必填-->
        <span v-else class="filter-header-title">
          <span style="color: red">*</span>
          <el-icon :size="14" v-if="column.editRender && editConfig?.enabled">
            <Edit />
          </el-icon>
          {{ column.title }}
        </span>
        <div v-if="column.params?.moreTitle" class="first-col">
          <div class="first-col-top">
            {{ column.params?.topTitle }}
          </div>
          <div class="first-col-bottom">
            {{ column.params?.bottomTitle }}
          </div>
        </div>
      </template>
      <!-- 操作列 -->
      <template #operation_default="{ row, column, rowIndex }">
        <el-button
          v-for="item in column.params"
          v-show="hasPermi([item.hasPermi])"
          :key="item.title"
          :disabled="item?.setDisabled?.(row) ?? false"
          :icon="
            item.saveIcon && xGrid.isActiveByRow(row)
              ? item.saveIcon
              : item.icon
          "
          circle
          size="small"
          style="padding: 6px"
          :title="
            item.saveTitle && xGrid.isActiveByRow(row)
              ? $t(item.saveTitle)
              : $t(item.title)
          "
          :type="item.type"
          plain
          @click.stop="item?.click?.(row, xGrid.isActiveByRow(row), rowIndex)"
        />
      </template>
      <!-- radio -->
      <template #radio_edit="{ row, column }">
        <el-radio-group
          @change="column.params?.change?.(row)"
          v-model="row[column.field]"
        >
          <el-radio :value="column.params?.trueValue ?? '1'" />
        </el-radio-group>
      </template>
      <!-- checkBox -->
      <template #checkbox_edit="{ row, column }">
        <el-checkbox
          :true-value="column.params?.truelabel ?? 1"
          :false-value="column.params?.falselabel ?? 0"
          @change="column.params?.change?.(row)"
          fill="#eb5c20"
          v-model="row[column.field]"
        />
      </template>
      <!-- 省市区 -->
      <template #provinceCityArea_edit="{ row, column }">
        <ErrorTooltip :validErrors="validErrors" :field="column.field">
          <!-- <select-area-pop
            :data="row[column.field]"
            :disabled="column.params?.disabled ?? false"
            @handle-submit="
              (val) => {
                column.params?.change?.(val, row);
                row[column.field] = val;
              }
            "
          /> -->
        </ErrorTooltip>
      </template>
      <!-- 高级日期查询控件 -->
      <template #advance_date_picker_edit="{ row, column }">
        <!-- <ErrorTooltip :validErrors="validErrors" :field="column.field">
          <base-date-time-picker
            v-model="row[column.field]"
            :type="column.params?.dateType ?? 'date'"
            :disabledDate="column.params?.disabledDate"
            :valueFormat="column.params?.valueFormat"
            :shortcuts="column.params?.shortcuts"
            :monthShortcut="column.params?.monthShortcut"
            :field="column.field"
            :datepickerStyle="column.params?.datepickerStyle"
            :formDataSubmit="column.params?.formDataSubmit"
            :selectableRangeConfig="column.params?.selectableRangeConfig"
            @handle-time-change="column.params?.change?.(row, column)"
            @change-range-date="column.params?.change?.(row, column)"
          />
        </ErrorTooltip> -->
      </template>

      <!-- 标签展示 -->
      <template #icon_default="{ row, column }">
        <span class="table-status">
          <i
            v-if="column.params?.color"
            :class="column.params?.color?.[row[column.field]]"
          ></i>
        </span>
      </template>
      <!-- 状态列 -->
      <template #status_default="{ row, column }">
        <span class="table-status">
          <i
            v-if="column.params?.color"
            :class="column.params?.color?.[filterStatusRows(row, column).value]"
          ></i>
          {{ filterStatusRows(row, column).label }}
        </span>
      </template>
      <!-- 状态列 -->
      <template #switch_default="{ row, column }">
        <vxe-switch
          v-model="row[column.field]"
          :open-label="column.params?.openLabel ?? ''"
          :open-value="column.params?.openValue ?? ''"
          :close-label="column.params?.closeLabel ?? ''"
          :close-value="column.params?.closeValue ?? ''"
          :disabled="column.params?.disabled ?? false"
          color="#000"
          @change="column.params?.change?.(row)"
          @click.stop
        />
      </template>
      <!-- 工作分工规则多配置下拉框 -->
      <template #config_select_edit="{ row, column }">
        <el-popover
          placement="bottom-start"
          trigger="click"
          :ref="(el) => handleSetMap(el, column.field)"
          :popper-style="{ padding: '20px 16px' }"
          :width="280"
          :show-arrow="false"
        >
          <template #reference>
            <vxe-input
              v-if="
                !row[column.field]?.group?.filter((item) => item.checked)
                  ?.length &&
                !row[column.field]?.valueList?.filter((item) => item.checked)
                  ?.length
              "
              :disabled="column.params?.disabled"
              @focus="
                column.params?.handleChange(row, column, row[column.field])
              "
              type="text"
              :maxlength="column.params?.maxlength"
              :placeholder="column.params?.placeholder ?? $t('请选择')"
            />
            <div
              class="config-line"
              @click="
                column.params?.handleChange(row, column, row[column.field])
              "
              v-else
            >
              <!-- 工作组 -->
              <div
                class="config-line-group"
                v-for="(items, i) in row[column.field]?.group?.filter(
                  (item) => item.checked
                )"
                :key="i"
              >
                {{ items?.label }}
              </div>
              <!-- 具体属性值。。。 -->
              <div
                class="config-line-port"
                v-for="(items, i) in row[column.field]?.valueList?.filter(
                  (item) => item.checked
                ) || []"
                :key="i"
              >
                {{ items?.label + ";" }}
              </div>
            </div>
          </template>
          <div class="select-content">
            <div class="select-content-tip">{{ $t("工作组") }}</div>
            <div v-for="(items, i) in row[column.field]?.group" :key="i">
              <el-checkbox v-model="items.checked">{{
                items.label
              }}</el-checkbox>
            </div>
            <el-divider />
            <div class="select-content-tip">
              {{ $t(column.params?.options?.name) }}
            </div>
            <div
              v-for="(items, i) in row[column.field]?.valueList || []"
              :key="i"
            >
              <el-checkbox :disabled="items.disabled" v-model="items.checked">{{
                items.label
              }}</el-checkbox>
            </div>
            <footer>
              <el-button @click="handleCancelPopver(column.field)" size="small">
                {{ $t("取消") }}
              </el-button>
              <el-button
                @click="handleConfirmPopver(column.field)"
                type="primary"
                size="small"
              >
                {{ $t("确定") }}
              </el-button>
            </footer>
          </div>
        </el-popover>
      </template>
      <!-- 编辑 -->
      <template #input_edit="{ row, column }">
        <ErrorTooltip :validErrors="validErrors" :field="column.field">
          <vxe-input
            style="width: 100%"
            v-model="row[column.field]"
            :type="column.params?.type ?? 'text'"
            :disabled="
              column.params?.disabled ||
              (column.params?.noEdit && row[column.params?.noEditFlag])
            "
            v-thousands="{
              enable: column.params?.thousands || false,
              value: row[column.field],
            }"
            @blur="column.params?.handleBlur?.($event, row)"
            @input="column.params?.handleInput?.($event, row)"
            @change="column.params?.handleChange?.($event, row)"
            :min="column.params?.min"
            :max="column.params?.max"
            :digits="column.params?.digits"
            :maxlength="column.params?.maxlength"
            :placeholder="column.params?.placeholder ?? $t('请输入')"
          >
            <!-- <template #suffix>
            <el-tooltip
              placement="top"
              effect="light"
              :content="tooltipContent"
            >
              <span
                v-if="errorObject && errorObject[column.field]"
                style="color: red"
                >!</span
              >
            </el-tooltip>
          </template> -->
          </vxe-input>
        </ErrorTooltip>
      </template>
      <template #input_autocomplete="{ row, column }">
        <ErrorTooltip :validErrors="validErrors" :field="column.field">
          <el-autocomplete
            v-model="row[column.field]"
            :fetch-suggestions="
              (val, cb) => {
                querySearchAsync(val, cb, column.params);
              }
            "
            popper-class="vxe-table--ignore-clear"
            clearable
            :placeholder="$t(column.placeholder || '请输入')"
            @select="handleAutocompleteSelect($event, column.params, row)"
            @clear="handleAutocompleteClear(column.params, row)"
          >
          </el-autocomplete>
        </ErrorTooltip>
      </template>
      <!-- 点击展开textarea弹框的输入框 -->
      <template #popoverTextarea_edit="{ row, column }">
        <ErrorTooltip :validErrors="validErrors" :field="column.field">
          <el-popover
            placement="bottom"
            :width="240"
            style="padding: 10px"
            :visible="popoverVisible"
            trigger="click"
          >
            <template #reference>
              <vxe-input
                v-model="row[column.field]"
                type="text"
                :disabled="column.params?.disabled"
                @focus="popoverInputFocus(row[column.field])"
                >{{ column.params }}</vxe-input
              >
            </template>
            <div>
              <el-input
                v-model="popoverTextarea"
                style="width: 100%; margin: auto"
                :rows="8"
                :placeholder="$t('请输入备注')"
                type="textarea"
              />
              <el-divider style="width: 110%; margin: 19px -12px 15px" />
              <div class="popover-div">
                <el-button text class="btn" @click="popoverCancel">{{
                  $t("取消")
                }}</el-button>
                <el-button
                  text
                  class="btn confirm"
                  @click="popoverConfirm(row, column.field)"
                  >{{ $t("确认") }}</el-button
                >
              </div>
            </div>
          </el-popover>
        </ErrorTooltip>
      </template>
      <template #province_city_area_edit="{ row, column }">
        <ErrorTooltip :validErrors="validErrors" :field="column.field">
          <ProvinceCityArea
            v-model:propSelectCode="row[column.field]"
            v-model:prop="row[column.params.prop]"
            :propsSelect="column.params.propsSelect"
            :propSelectPlaceholder="column.params.propSelectPlaceholder"
            :clearable="column.params.clearable"
            :multiple="column.params.multiple"
            :cascaderProps="column.params.props"
            :placeholder="column.params.placeholder"
            @onPropSelectClose="onPropSelectClose(column, row)"
            @onPropSelectChange="
              (value, data) => {
                onPropSelectChange(value, data, column, row);
              }
            "
            @onCascaderClose="onCascaderClose(column, row)"
            @onCascaderChange="
              (data, value) => {
                onCascaderChange(data, value, column, row);
              }
            "
          >
          </ProvinceCityArea>
        </ErrorTooltip>
      </template>
      <template #select_edit="{ row, rowIndex, column }">
        <ErrorTooltip :validErrors="validErrors" :field="column.field">
          <vxe-select
            style="width: 100%"
            :transfer="column.params?.transfer || false"
            :disabled="
              column.params?.disabled ||
              (column.params?.noEdit &&
                row[column.params?.noEditFlag] !==
                  column.params?.canEditCode) ||
              (column.params?.noEdit &&
                row[column.params?.noEditFlag] &&
                row[column.params?.not])
            "
            :clearable="column.params?.clearable"
            :multiple="column.params?.multiple"
            v-model="row[column.field]"
            :empty-text="column.params?.emptyText ?? '暂无数据'"
            @change="onChange($event, rowIndex, row, column)"
            @clear="onClear(column, row)"
          >
            <vxe-option
              v-for="item in column.params.options"
              :key="
                column.params?.value ? item[column.params?.value] : item.value
              "
              :disabled="item.disabled"
              :value="
                column.params?.value
                  ? item[column.params?.value]
                  : item.value || item.label
              "
              :label="
                column.params?.label ? item[column.params?.label] : item.label
              "
            />
          </vxe-select>
        </ErrorTooltip>
      </template>
      <template #switch_edit="{ row, column }">
        <!-- swich -->
        <vxe-switch
          v-model="row[column.field]"
          :open-label="column.params?.openLabel ?? ''"
          :open-value="column.params?.openValue ?? ''"
          :close-label="column.params?.closeLabel ?? ''"
          :close-value="column.params?.closeValue ?? ''"
        />
      </template>
      <template #datePick_edit="{ row, column }">
        <ErrorTooltip :validErrors="validErrors" :field="column.field">
          <vxe-input
            :transfer="true"
            v-model="row[column.field]"
            :placeholder="$t('开始日期')"
            :type="column.params?.attr?.type ?? 'date'"
          />
        </ErrorTooltip>
      </template>
      <template #dateRangePick_edit="{ row, column }">
        <ErrorTooltip :validErrors="validErrors" :field="column.field">
          <vxe-input
            :transfer="true"
            v-model="row[column.params?.props?.startfield]"
            :placeholder="$t('开始日期')"
            :type="column.params?.attr?.type ?? 'date'"
            :disabled-method="
              ({ date }) => {
                const endDate = row[column.params?.props?.endfield];
                if (endDate) {
                  return date.getTime() > new Date(endDate).getTime();
                }
                return false;
              }
            "
            class="pick-data-input"
          />
          ~
          <vxe-input
            :transfer="true"
            v-model="row[column.params?.props?.endfield]"
            :placeholder="$t('结束日期')"
            :type="column.params?.attr?.type ?? 'date'"
            :disabled-method="
              ({ date }) => {
                const startDate = row[column.params?.props?.startfield];
                if (startDate) {
                  return date.getTime() < new Date(startDate).getTime();
                }
                return false;
              }
            "
            class="pick-data-input"
          />
        </ErrorTooltip>
      </template>
      <template #timePick_edit="{ row, column }">
        <ErrorTooltip :validErrors="validErrors" :field="column.field">
          <el-date-picker
            :transfer="true"
            v-model="row[column.field]"
            :type="column.params?.dateType ?? 'date'"
            :style="column.params?.style"
            clearable
            :format="column.params?.format ?? 'HH:mm'"
            :format-show="column.params?.format ?? 'HH:mm'"
            :value-format="column.params?.valueFormat ?? 'YYYY-MM-DD HH:mm:ss'"
            :placeholder="$t('选择时间')"
          />
        </ErrorTooltip>
      </template>
      <template #other_default="scope">
        <slot
          :name="`table-${scope.column.field}`"
          v-bind="scope"
          :validErrors="validErrors"
        ></slot>
      </template>
      <!-- 拖动插槽 -->
      <template #drag_default="{ row, column }">
        <!-- <span
          class="close-btn"
          v-if="row && column.params && column.params.showCloseBtn"
          @click="delRow(row)"
        >
          x
        </span> -->
        <div>
          <span
            class="vxe-icon-close"
            style="cursor: pointer"
            v-if="
              row &&
              column.params?.showCloseBtn &&
              row[column.params?.notNullProp]
            "
            @click="delRow(row)"
          ></span>
          <span
            class="drag-btn"
            style="margin-left: 5px; cursor: pointer"
            v-if="row?.[column.params?.notNullProp]"
          >
            <SvgIcon icon-class="icon-drag" size="16px" />
          </span>
        </div>
      </template>
    </vxe-grid>
    <el-image
      ref="pickImages"
      style="position: absolute"
      :preview-src-list="srcList"
    >
      <template #error>
        <div class="image-slot"><i></i></div>
      </template>
    </el-image>
    <!-- destroy-on-close设置为true，防止一个页面出现多个table，导致拖拽无效的问题 -->
    <el-drawer
      v-model="drawerVisible"
      direction="rtl"
      :size="300"
      :title="i18n.global.t('字段配置')"
    >
      <el-checkbox-group
        :id="fieldModuleId"
        class="field-module"
        v-model="checkFieldList"
        @change="formatTbCol"
      >
        <div
          v-for="item in filedColumns"
          class="drag-item"
          :key="item.field"
          :data-rid="item.field"
        >
          <span class="drag-item-handle">
            <Svg-icon icon-class="icon-drag" size="20px" />
          </span>
          <el-checkbox
            v-if="item.field !== FIXED_COLUMN_DATA.field"
            class="field-part"
            :label="item.field"
          >
            {{ item.title }}
          </el-checkbox>
          <div v-else class="isFixed">{{ item.title }}</div>
        </div>
      </el-checkbox-group>
      <div class="foot-btn">
        <!-- <el-button @click="handleSaveField" class="save-btn">{{
          $t("保存")
        }}</el-button> -->
        <el-button @click="drawerVisible = false" class="cancel-btn">{{
          $t("关闭")
        }}</el-button>
      </div>
    </el-drawer>
    <div
      class="setting-icon"
      @click="addColumnDropOpen()"
      v-show="props.moduleName"
    >
      <el-icon style="width: 18px; height: 18px"><Setting /></el-icon>
      <!-- <span class="text"> {{ $t("自定义列") }}</span> -->
    </div>
  </div>
</template>
<script setup>
import {
  ref,
  reactive,
  watch,
  onMounted,
  nextTick,
  computed,
  onBeforeUnmount,
} from "vue";
import i18n from "@/lang/index";
import {
  setDialogTableHeight,
  hasPermi,
  setTableHeight,
  debounce,
} from "@/utils/mUtils";
// import { conditionList, saveBatchAdd } from "@/api/baisc-data/customers";
import Sortable from "sortablejs";
import { hEmitter, cEmitterEvent } from "@/helpers/index.js";
import { COMMON } from "@/consts/common.js";
import ErrorTooltip from "./components/ErrorTooltip.vue";
import { tableProps } from "./props";
import { generateId } from "./utils";
import { NumberUtils } from "@/utils/number.js";
import { isNumber } from "@/utils/is.js";
import {
  getLocalStorage,
  removeLocalStorage,
  setLocalStorage,
} from "@/utils/cache.js";
import { useRoute } from "vue-router";
const route = useRoute();
const popoverRefMap = ref({});
function handleCancelPopver(field) {
  popoverRefMap.value[`popoverRef${field}`]?.hide();
}
function handleSetMap(el, field) {
  popoverRefMap.value[`popoverRef${field}`] = el;
}
function handleConfirmPopver(field) {
  popoverRefMap.value[`popoverRef${field}`]?.hide();
}
const props = defineProps(tableProps);
const emit = defineEmits([
  "onEnd",
  "delRow",
  "handlePageChange",
  "handleSelectionChange",
  "checkboxChange",
  "checkboxAll",
  "radioChange",
  "handleCurrentChange",
  "handleCellClick",
  "handleEditClosed",
  "handleCellDblclick",
  "handleKeydown",
  "toggleTreeExpand",
  "editActivated",
  "onChangeEditRow",
  "rowInsertDragend",
]);
/** 栏位分割线column数据 */
const FIXED_COLUMN_DATA = {
  field: "split",
  title: "栏位锁定分割线",
};
const xGrid = ref();
const validErrors = ref({});
const currentEditRowObj = reactive({
  isEdit: false,
});

// table可以冻结列的最大个数（必须限制，否则如果设置太多的冻结列，会导致出现横向滚动条，布局错乱）
const maxFixedSizeCount = ref(4);
const pickImages = ref();
const height = ref(
  props.showRows ? calcHeight(undefined, props.showRows, props.pageVo) : 450
);
const changePage = ref(false);
const langRule = reactive({});
const showHeaderFilter = ref(true);
const srcList = ref([]);
const columns_data = ref([]);
const drawerVisible = ref(false);
/** 自定义列配置列表数据(默认不显示没有title、field属性column对应的列) */
const filedColumns = ref([]);
// 用户未保存过字段配置时，在初始化时需要隐藏下面这些列（用户勾选显示才显示）
const filedColumnsNeedHideInFirst = [
  // "createByName",
  // "createTime",
  // "updateByName",
  // "updateTime",
];
const checkFieldList = ref([]);
const highlightedRow = ref(false);
const popoverVisible = ref(false); // 点击输入框弹出popover
const fieldModuleId = `fieldModuleId-${generateId()}`;

const page = computed(() => ({ ...props.pageVo }));
/** 整合汇总后的字段作为一个新的对象传出去 */
const sumDataObject = {};
const popoverTextarea = ref("");
/** 输入框点击聚焦时弹出弹框 */
function popoverInputFocus(val) {
  popoverTextarea.value = val;
  popoverVisible.value = true;
}
// 列表的列
let headerColumns = computed(() => {
  return (
    props.columns
      .map((item, index) => {
        if (item.type === "checkbox" || index === props.columns.length - 1) {
          item.resizable = false;
        }
        if (item.type === "checkbox") {
          item.width = 50;
        }
        return {
          ...item,
          title: i18n.global.t(item.title || ""),
          // 显式的配置sortable=false则不显示排序按钮，否则默认显示排序图标
          sortable: item.sortable === true || item.sortable === undefined,
        };
      })
      // 处理隐藏列
      .filter((el) => !el.hidden)
  );
});

// 是否显示表尾
const showFooter = computed(() => {
  return (
    (props.footerData && props.footerData.length > 0) ||
    headerColumns.value.find((el) => el.showSummary || el.summaryTitle) !==
      undefined
  );
});
const globalClass = computed(() => [
  "animate__animated",
  {
    ["animate__" + props.showAnimate]: props.showAnimate !== "",
  },
]);

/** 动态计算表格的最大高度（根据maxRow计算） */
const innerMaxHeight = computed(() => {
  return calcHeight(props.maxHeight, props.maxShowRows, props.pageVo);
});
/** 动态计算表格的最大高度（根据maxRow计算） */
const innerMinHeight = computed(() => {
  return calcHeight(props.minHeight, props.minShowRows, props.pageVo);
});

function calcHeight(height, rows, pageVo) {
  if (height) return height;
  if (rows) {
    const tableHeaderHeight = 40; // 表头高度
    const rowHeight = 32; // 每一行的高度
    const pagerHeight = pageVo ? rowHeight : 0;
    return tableHeaderHeight + rows * rowHeight + pagerHeight;
  }
  return null;
}

/** 配置treeConfig的默认参数 */
const innerTreeConfig = computed(() => {
  if (props.treeConfig) {
    const defaultValue = {};
    return {
      ...defaultValue,
      ...props.treeConfig,
    };
  }
  return props.treeConfig;
});

const tableStyle = computed(() => {
  const style = {};
  const { marginTop } = props;
  if (marginTop === true) {
    Object.assign(style, { marginTop: "64px" });
  } else if (isNumber(marginTop)) {
    Object.assign(style, { marginTop: `${marginTop}px` });
  }
  return style;
});

/** 弹框取消删除textarea的值并关闭弹框 */
function popoverCancel() {
  clearEdit();
  popoverTextarea.value = "";
}
/** 弹框确认修改某字段 */
function popoverConfirm(row, prop) {
  row[prop] = popoverTextarea.value;
  popoverTextarea.value = "";
  clearEdit();
}

// 列拖动
function rowDrop() {
  nextTick(() => {
    let tbody = xGrid.value.$el.querySelector(
      ".body--wrapper>.vxe-table--body tbody"
    );
    Sortable.create(tbody, {
      handle: ".drag-btn",
      onEnd: (e) => {
        emit("onEnd", e, props.extraParams);
      },
    });
  });
}

// 调整列表高度
function _adjustTableHeight() {
  const isEmpty = !props.dataSource?.length;
  if (innerMaxHeight.value) {
    // 如果设置了maxHeight且数据不为空，那么就设置height=0，实现高度随着内容自适应效果（最大不超过maxHeight）
    height.value = isEmpty ? props.defaultHeight || innerMaxHeight.value : 0;
  } else if (props.showRows) {
    height.value = calcHeight(undefined, props.showRows, props.pageVo);
  } else if (props.setHeight) {
    height.value = props.setHeight;
  } else {
    if (props.tableType === "dialogTable") {
      height.value =
        setDialogTableHeight() > 400 ? setDialogTableHeight() : 400;
    } else if (props.tableType === "formTable") {
      height.value = 0;
    } else {
      /** 20兼容page 的margin的值 */

      height.value = setTableHeight() - props.subtractTableHeight;
    }
  }
}

const adjustTableHeight = debounce(_adjustTableHeight, 100);

function delRow(row) {
  emit("delRow", row, props.extraParams);
}
function handlePageChange({ currentPage, pageSize }) {
  changePage.value = true;
  emit("handlePageChange", { currentPage, pageSize });
}
// 当表格被激活且键盘被按下结束时会触发的事件
function handleKeydown(e) {
  emit("handleKeydown", e);
}
function cellDblclick({ row }) {
  emit("handleCellDblclick", row);
}
const preEditRow = ref({});
// 行改变值时触发
async function handleCurrentChangeSubmit({ row }) {
  const isEdit = xGrid.value.isEditByRow(row);
  // 如果不需要触发提交,此功能必须keepSource和changeEditNeedTrigger为true时才有效
  if (!props.changeEditNeedTrigger || !props.keepSource) {
    return isEdit;
  }
  if (isEdit) {
    preEditRow.value = { ...row };
  }
  // 获取修改行
  const updateRows = xGrid.value.getUpdateRecords();
  // 获取新增行
  const insertRows = xGrid.value.getInsertRecords();
  const noEmptyPreEditRow = Object.keys(preEditRow.value).length;
  const changesRows = [...updateRows, ...insertRows];
  if (!isEdit && noEmptyPreEditRow) {
    const updatedRow = changesRows.find(
      (item) => item.id === preEditRow.value.id
    );
    // 如果是编辑状态，且有修改过数据,则提交
    if (updatedRow) {
      const isError = await xGrid.value.fullValidate([updatedRow]);
      if (isError) {
        const isEdit = xGrid.value.isEditByRow(updatedRow);
        !isEdit && xGrid.value.setEditRow(updatedRow);
      }
      !isError && emit("onChangeEditRow", updatedRow);
    }
    preEditRow.value = {};
  }
  return isEdit;
}

function myCheckboxMethod({ row }) {
  const canCheck = props.checkboxMethod({ row });
  row._checkedboxDisabled = !canCheck;
  return canCheck;
}

async function afterEditMethod({ row, ...rest }) {
  const rowId = xGrid.value.getRowid(row);
  const currentEditRow = xGrid.value.$el.querySelector(
    `.vxe-body--row[rowid="${rowId}"]`
  );
  currentEditRowObj.row = row;
  currentEditRowObj.dom = currentEditRow;
  !rest.column.disabled && xGrid.value.setEditCell(row, rest.column);
  const isEdit = await handleCurrentChangeSubmit({ row });
  currentEditRowObj.isEdit = isEdit;
}

async function cellClick({ row, ...rest }) {
  emit("handleCellClick", row, rest);
  const isEdit = await handleCurrentChangeSubmit({ row });
  if (!!isEdit) {
    return;
  }
  if (props.selectRowBySingleClick) {
    const selectedRows = xGrid.value.getCheckboxRecords();
    // 被禁用的不可以选中
    !row._checkedboxDisabled &&
      setCheckboxRow(
        row,
        !selectedRows.some((selectedRow) => selectedRow.id === row.id)
      );
  } else {
    if (highlightedRow.value) {
      xGrid.value.clearCurrentRow();
      highlightedRow.value = false;
    } else {
      highlightedRow.value = true;
    }
  }
}
// 表头单元格被点击时会触发该回调函数
function handleHeaderCellClick() {
  if (xGrid.value.getCurrentColumn()) {
    nextTick(() => {
      // DOM更新完成后
      xGrid.value.clearCurrentColumn();
    });
  }
}
function handleEditClosed({ row, rowIndex }) {
  const updateRows = xGrid.value.getUpdateRecords();
  if (!updateRows.length) {
    return;
  }

  const update = updateRows.find((updateRow) => updateRow.id === row.id);
  if (!update) return;
  new Promise((resolve, reject) => {
    emit("handleEditClosed", { ...row }, rowIndex, resolve, reject, xGrid);
  })
    .then((res) => {
      xGrid.value.reloadRow(row);
    })
    .catch((err) => {
      xGrid.value.setEditCell(row, props.keepSourceKey);
    });
}
function handColumnDragend({ newColumn }) {
  setTimeout(() => {
    let colList = hideColumns(headerColumns.value);
    initCustomColumnData(colList, []);
  }, 500);
}
function editActivated({ row, rowIndex }) {
  rowFullValidEvent(row);
  emit("editActivated", row);
}
// 清空选中状态
function clearAll() {
  xGrid.value && xGrid.value.clearAll();
  emit("handleSelectionChange", []);
}
// 状态过滤
function filterStatusRows(row, column) {
  const data = column.filters.find((item) => item.value === row[column.field]);
  return data || {};
}
function reloadTreeExpand(row) {
  xGrid.value.reloadTreeExpand(row);
}
function remove(rows) {
  xGrid.value.remove(rows);
}
function setCheckboxRow(rows, checked) {
  xGrid.value.setCheckboxRow(rows, checked);
  const list = [
    ...xGrid.value.getCheckboxReserveRecords(),
    ...xGrid.value.getCheckboxRecords(),
  ];
  emit("handleSelectionChange", list);
}
function checkboxAll({ checked }) {
  const list = [
    ...xGrid.value.getCheckboxReserveRecords(),
    ...xGrid.value.getCheckboxRecords(),
  ];
  emit("checkboxAll", {
    checked,
    row: props.dataSource.concat(xGrid.value.getInsertRecords()),
  });
  emit("handleSelectionChange", list);
}
function checkboxChange({ checked, row }) {
  const list = [
    ...xGrid.value.getCheckboxReserveRecords(),
    ...xGrid.value.getCheckboxRecords(),
  ];
  emit("handleSelectionChange", list);
  emit("checkboxChange", { checked, row });
}
function checkboxRangeSelect({ rangeRecords }) {
  emit("handleSelectionChange", rangeRecords);
}
function rowInsertDragend({ oldRow }) {
  emit("rowInsertDragend", oldRow);
}
function radioChange(data) {
  emit("radioChange", data);
}
function getCheckboxRecords(isFull = false) {
  return xGrid.value.getCheckboxRecords(isFull);
}
function getCheckboxReserveRecords(isFull = false) {
  return xGrid.value.getCheckboxReserveRecords(isFull);
}
function getCheckboxIndeterminateRecords(isFull = false) {
  return xGrid.value.getCheckboxIndeterminateRecords(isFull);
}
function clearCheckboxRow() {
  xGrid.value.clearCheckboxRow();
  emit("handleSelectionChange", []);
}
function clearRadioRow() {
  xGrid.value.clearRadioRow();
}
function editRowEvent(row) {
  const $grid = xGrid.value;
  $grid.setActiveRow(row);
}
function filterEvent(option) {
  // 设置为选中状态
  option.checked = true;
  // 修改条件之后，需要手动调用 updateData 处理表格数据
  xGrid.value.updateData();
}
const querySearchAsync = async (queryString, cb, c) => {
  if (!queryString) return cb([]);
  const params = {};
  params[c.queryKey] = queryString;
  const fun = c.apiModule || (() => {});
  let res = await fun({
    ...params,
  });
  const data = c.options || res.data || res.rows || [];
  const arr = data.map((item) => {
    const obj = {
      ...item,
    };
    if (!c.labelKey) {
      obj["value"] = obj[c.value];
    } else {
      const strArr = [];
      for (const key in c.labelKey) {
        obj[key] && strArr.push(obj[key]);
      }
      obj["value"] = strArr.join(c.joinStr || ",");
    }
    return {
      ...obj,
    };
  });
  cb(arr);
};
const handleAutocompleteSelect = (val, c, row) => {
  if (c.paramsKey) {
    for (const key in c.paramsKey) {
      row[key] = val[c.paramsKey[key]];
    }
  }
  c.onSelect && c.onSelect(val, c, row);
};
const handleAutocompleteClear = (c, row) => {
  if (c.paramsKey) {
    for (const key in c.paramsKey) {
      row[key] = null;
    }
  }
};
// 校验规则多语言处理
function getLangRule() {
  const ruleObj = {};
  if (props.editRules) {
    Object.keys(props.editRules).forEach((key) => {
      let obj;
      if (props.editRules[key] instanceof Array) {
        obj = props.editRules[key].map((it) => ({
          ...it,
          message: it.message ? i18n.global.t(it.message) : "",
        }));
      } else {
        obj = {
          ...props.editRules[key],
          message: props.editRules[key].message
            ? i18n.global.t(props.editRules[key].message)
            : "",
        };
      }
      ruleObj[key] = obj;
    });
    Object.assign(langRule, ruleObj);
  }
}
function onClick(url) {
  srcList.value = [];
  srcList.value.push(`${window.location.origin}/api${url}`);
  pickImages.value.showViewer = true;
}
// 列表校验
const validEvent = async () => {
  const $table = xGrid.value;
  if ($table) {
    return await $table.validate(true);
  }
};

const rowFullValidEvent = async (row) => {
  const $table = xGrid.value;
  if ($table) {
    const errors = await $table.fullValidate(row ? row : true);
    const fields = (errors && Object.keys(errors)) || [];
    const obj = fields.reduce((pre, field) => {
      const item = errors[field];
      const message = item?.[0]?.rule?.message;
      pre[field] = message;
      return pre;
    }, {});
    validErrors.value = obj;
    return errors;
  }
};

async function addColumnDropOpen() {
  drawerVisible.value = true;
  bindDragEventForColumns();
}

/** 根据自定义列的顺序（dom结构顺序），同步到table的列顺序上 */
function formatTbCol() {
  const $table = xGrid.value;
  const { fullColumn } = $table.getTableColumn();
  const fieldModule = document.getElementById(fieldModuleId);
  // 拖拽后-自定义列表的新顺序
  const newCols = Array.from(fieldModule.querySelectorAll("[data-rid]")).map(
    (el) => filedColumns.value.find((v) => v.field === el.dataset.rid)
  );
  const fixedIdx = newCols.findIndex(
    (item) => item.field === FIXED_COLUMN_DATA.field
  );
  const newFiledColumns = [...newCols];
  let fixedCol = [];

  if (fixedIdx !== -1) {
    fixedCol = newCols.slice(0, fixedIdx);
    newCols.splice(fixedIdx, 1);
  }
  // 调整自定义的顺序
  // 设置冻结列和那些列需要显示
  fullColumn.forEach((col) => {
    col.fixed =
      isIgnoreCustomConfigColumn(col) ||
      fixedCol.some((v) => v.field === col.field)
        ? "left"
        : null;
    col.visible =
      isIgnoreCustomConfigColumn(col) ||
      checkFieldList.value.some((v) => v === col.field);
  });
  // 根据自定义列，对table列进行排序
  for (let i = 0; i < fullColumn.length; i++) {
    const col = fullColumn[i];
    const newCol = newCols[0];
    if (!newCol || !col.title || !col.field || !col.visible) continue;
    if (col.field === newCol.field) {
      newCols.shift();
      continue;
    }
    const idx = fullColumn
      .slice(i + 1)
      .findIndex((v) => v.field === newCol.field);
    if (!~idx) {
      newCols.shift();
      i--;
      continue;
    }
    fullColumn[i] = fullColumn[idx + i + 1];
    fullColumn[idx + i + 1] = col;
    newCols.shift();
  }

  filedColumns.value = newFiledColumns; // 设置新的顺序
  const VXE_CUSTOM_STORE = getLocalStorage("VXE_CUSTOM_STORE") || {};
  if (VXE_CUSTOM_STORE[`xGrid${props.tableId}`]) {
    VXE_CUSTOM_STORE[`xGrid${props.tableId}`].sortData = fullColumn.map(
      (item) => ({
        k: item.type === "checkbox" ? "type=checkbox" : item.field,
      })
    );
  }
  setLocalStorage("VXE_CUSTOM_STORE", VXE_CUSTOM_STORE);
  $table && $table.loadColumn(fullColumn);
}

function formatTbCol2(fullColumn, remoteColumns) {
  remoteColumns = [...remoteColumns];
  const fixedColumns = remoteColumns.filter((v) => v.fixedFlag);
  fullColumn.forEach((col) => {
    col.fixed =
      isIgnoreCustomConfigColumn(col) ||
      fixedColumns.some((v) => v.queryField === col.field)
        ? "left"
        : null;
    col.visible =
      isIgnoreCustomConfigColumn(col) ||
      remoteColumns.some(
        (v) => v.queryField === col.field && isVisibleColumn(v)
      );
  });

  for (let i = 0; i < fullColumn.length; i++) {
    const col = fullColumn[i];
    const newCol = remoteColumns[0];
    if (!newCol || !col.title || !col.field || !col.visible) continue;
    if (col.field === newCol.queryField) {
      remoteColumns.shift();
      continue;
    }
    const idx = fullColumn
      .slice(i + 1)
      .findIndex((v) => v.field === newCol.queryField);
    if (!~idx) {
      remoteColumns.shift();
      i--;
      continue;
    }
    fullColumn[i] = fullColumn[idx + i + 1];
    fullColumn[idx + i + 1] = col;
    remoteColumns.shift();
  }
  return fullColumn;
}

/** 后台配置是否显示该列（通过remark字段判断） */
const isVisibleColumn = (col) =>
  col.remark === COMMON.True || col.remark == null;

// 绑定拖拽事件，实现列拖拽
function bindDragEventForColumns() {
  nextTick(() => {
    const fieldModule = document.getElementById(fieldModuleId);
    fieldModule &&
      Sortable.create(fieldModule, {
        handle: ".drag-item-handle",
        onEnd: formatTbCol,
        onMove: (evt) => {
          // 当前是否正在拖拽固定列
          const isDragFixedColumn =
            evt.dragged.dataset.rid === FIXED_COLUMN_DATA.field;

          const all = Array.from(fieldModule.querySelectorAll(".drag-item"));
          const dropIndex = all.findIndex((el) => el === evt.related);
          const fixedColumnIndex = all.findIndex(
            (el) => el.dataset.rid === FIXED_COLUMN_DATA.field
          );
          if (isDragFixedColumn) {
            // 栏位锁定分割线的位置，如果超过最大可冻结列的个数那么禁止拖拽成功
            if (dropIndex > maxFixedSizeCount.value) {
              maxFixedSizeCountTip();
              return false;
            }
          } else {
            // 如果拖拽到了栏位分隔栏的上面同时排序后的冻结列个数超过了最大值，也需要限制不可拖拽排序成功
            if (
              dropIndex <= fixedColumnIndex &&
              fixedColumnIndex + 1 > maxFixedSizeCount.value
            ) {
              maxFixedSizeCountTip();
              return false;
            }
          }
          return true;
        },
      });
  });
}

const maxFixedSizeCountTip = debounce(() => {
  ElMessage.warning(
    i18n.global.t(`固定项最多只能设置${maxFixedSizeCount.value}个`)
  );
}, 500);
function handleSaveField() {
  removeLocalStorage("VXE_CUSTOM_STORE");
  const $table = xGrid.value;
  setTimeout(() => {
    $table.refreshColumn();
    // toSaveBatchAdd();
  }, 500);
  drawerVisible.value = false;
}

// 获取列信息
async function getConditionList() {
  const $table = xGrid.value;
  if (props.moduleName) {
    let queryColumns = [];
    // 用户未字段配置时，隐藏掉初始化需要隐藏的字段
    let colList = hideColumns(headerColumns.value);
    // 初始化时，需要隐藏特定的列（filedColumnsNeedHideInFirst）
    checkFieldList.value = getEffectiveColumns(headerColumns.value)
      .filter((item) => !filedColumnsNeedHideInFirst.includes(item.field))
      .map((v) => v.field);
    try {
      queryColumns = [];
      if (queryColumns.length) {
        colList = formatTbCol2(headerColumns.value, queryColumns);
        checkFieldList.value = getEffectiveColumns(colList)
          .filter((item) => item.visible)
          .map((item) => item.field);
      }
    } catch (error) {}
    if ($table) {
      // 处理 headerColumns.value 变化时未更新params的问题
      colList.forEach((col) => {
        const headerCol = headerColumns.value.find(
          (item) => item.field === col.field
        );
        if (headerCol && col?.params) {
          col.params = headerCol.params;
        }
      });
      $table.loadColumn(colList);
    }
    initCustomColumnData(colList, queryColumns);
  }
}

/** 初始化自定义列的数据 */
function initCustomColumnData(fullColumns, remoteColumns) {
  const filterColumns = getEffectiveColumns(fullColumns);
  const arr = [];
  if (remoteColumns?.length) {
    // 过滤掉没有queryField值的数据（兼容以前版本checkbox也被保存到后台的情况，checkbox没有queryField值，checkbox是不参与自定义列配置的）
    remoteColumns = remoteColumns.filter((item) => item.queryField);
    const fixedIndex = remoteColumns.findLastIndex(
      (col) => col.fixedFlag === 1
    );
    arr.push(...filterColumns);
    arr.splice(fixedIndex + 1, 0, FIXED_COLUMN_DATA);
  } else {
    // 先添加冻结列-列表
    const fixedColumns = filterColumns.filter(({ fixed }) => fixed === "left");
    arr.push(...fixedColumns);
    arr.push(...filterColumns.filter((item) => !item.fixed));
    // 添加-栏位锁定分割线
    arr.splice(fixedColumns.length, 0, FIXED_COLUMN_DATA);
  }
  filedColumns.value = arr;
}
/** 隐藏指定的列 */
function hideColumns(columns) {
  const localStore = getLocalStorage("VXE_CUSTOM_STORE") || {};
  const localStoreColumns = localStore[`xGrid${props.tableId}`];

  if (localStoreColumns) {
    const arr = [];
    columns.forEach((col) => {
      const index = localStoreColumns.sortData.findIndex(
        (item) => item.k === col.field
      );
      arr[index] = {
        ...col,
        visible: filedColumnsNeedHideInFirst.includes(col.field)
          ? false
          : col.visible,
      };
    });
    return arr;
  }
  return columns.map((col) => {
    return {
      ...col,
      visible: filedColumnsNeedHideInFirst.includes(col.field)
        ? false
        : col.visible,
    };
  });
}
function toolbarToolClick({ type }) {
  if (type === "confirm") {
    // toSaveBatchAdd();
  }
}

function toSaveBatchAdd() {
  const $table = xGrid.value;
  const { fullColumn } = $table.getTableColumn();
  const columnList = getEffectiveColumns(fullColumn);
  // 将所有的column字段列表存到后台，通过remark: 1（选中） 0（未选中）判断是否选中
  const queryConditions = columnList.map((item) => ({
    queryField: item.field,
    queryFieldName: item.title,
    fixedFlag: item.fixed ? 1 : 0,
    /** 是否选中 */
    remark: checkFieldList.value.includes(item.field)
      ? COMMON.True
      : COMMON.False,
  }));
  saveBatchAdd({
    module: props.moduleName,
    queryColumns: queryConditions,
  });
}
const footerMethod = () => {
  // 返回一个二维数组的表尾合计
  // 若父组件有传入footerData，则直接使用，否则会根据columns里有showSummary 属性来生成汇总值
  if (props.footerData && props.footerData.length > 0) {
    return props.footerData;
  }
  const resFooterData = [
    [
      ...Array(
        headerColumns.value.filter((column) => column.visible !== false).length
      ).fill(""),
    ],
  ];
  let showFooterData = false;
  const listData = props.dataSource.concat(xGrid.value.getInsertRecords());
  headerColumns.value
    .filter((column) => column.visible !== false)
    .forEach((el, index) => {
      if (el.summaryTitle) {
        resFooterData[0][index] = el.summaryTitle;
        showFooterData = true;
      } else if (el.showSummary) {
        showFooterData = true;
        // relyField: 存在依赖汇总字段时设置，比如费用需要根据不同币种做汇总金额
        // 则设置成 relyField: "currency"
        let propSum;
        if (el.relyField) {
          // 初始化 relyFieldSumObject 对象, i.e. { USD:123, CNY:234 }
          const relyFieldSumObject = {};
          // 去重的field Set
          const uniqueRelyField = Array.from(
            new Set(listData.map((item) => item[el.relyField]))
          );
          uniqueRelyField.forEach((field) => {
            relyFieldSumObject[field] = listData
              .filter((item) => item[el.relyField] === field)
              .reduce((acc, item) => acc + Number(item[el.field]), 0);
          });
          // 处理汇总对象
          if (
            Object.entries(relyFieldSumObject) &&
            Object.entries(relyFieldSumObject).length
          ) {
            propSum = Object.entries(relyFieldSumObject)
              .map(
                ([currency, amount]) =>
                  `${currency} ${
                    el.params?.thousands
                      ? NumberUtils.format(amount ?? 0)
                      : amount
                  }`
              )
              .join(", ");
            // console.log(111, el.field, propSum);
            resFooterData[0][index] = propSum;
          }
        } else {
          propSum = listData.reduce(
            (prev, curr) => prev + Number(curr[el.field] || 0),
            0
          );
          // 根据column里params的digits来判断需要保留几位小数
          resFooterData[0][index] = sumDataObject[el.field] = Number(propSum)
            ? Number(propSum)?.toFixed((el.params && el.params.digits) ?? 2)
            : propSum;
          if (el.params?.thousands) {
            resFooterData[0][index] = NumberUtils.format(
              resFooterData[0][index] ?? 0
            );
          }
        }
      }
    });
  return showFooterData ? resFooterData : [[]];
};
function setAllTreeExpand(flag) {
  xGrid.value.setAllTreeExpand(flag);
}
function reloadData() {
  xGrid.value.reloadData(props.dataSource);
}
/** 更新表尾数据 */
function updateFooter() {
  xGrid.value.updateFooter();
}
/** 用于 edit-config，获取插入的临时数据 */
function getInsertRecords() {
  xGrid.value.getInsertRecords();
}
/** 手动清除单元格激活状态 */
function clearEdit() {
  xGrid.value.clearEdit();
}
/** 是否是忽略配置的自定义列（只要col.field或col.title有一个不存在，那么就忽略它，不加入自定义列配置，比如type=checkbox） */
function isIgnoreCustomConfigColumn(col) {
  return !col.field || !col.title;
}
/** 获取有效的自定义列-列表（会过滤掉title没有值column，有title的的才是可配置的column（设置冻结列和排序）） */
function getEffectiveColumns(allColumns) {
  return allColumns.filter((item) => !isIgnoreCustomConfigColumn(item));
}
/** 由于关闭了edit-config中的，autoClear:false,后点击别处时，无法触发edit-close */
function bindEventToTriggerEditClose(event) {
  const target = event.target;
  if (!target || !currentEditRowObj.isEdit) return;
  const classList = [...target.classList];
  const classListStr = classList.join(" ");
  if (
    !classListStr ||
    currentEditRowObj.dom?.contains(target) ||
    classListStr.indexOf("vxe-input--date-label") !== -1 ||
    classListStr.indexOf("vxe-select-option") !== -1 ||
    classListStr.indexOf("el-date-table-cell") !== -1 ||
    classListStr.indexOf("available") !== -1
  )
    return;
  xGrid.value.clearEdit();
}

watch(
  () => props.dataSource,
  () => {
    if (props.searchReserve) return;
    if (!changePage.value) {
      clearAll();
    } else {
      changePage.value = false;
    }
  }
);

// 实现当在一个table组件动态切换moduleName独立显示table字段时，可以缓存切换前临时设置的自定义列顺序（固定列）
const cacheMap = new Map();
watch(
  () => props.moduleName,
  (moduleName, oldModuleName) => {
    const data = cacheMap.get(moduleName);
    const cacheData = {
      checkFieldList: [...checkFieldList.value],
      filedColumns: [...filedColumns.value],
    };
    if (data) {
      // 加载缓存的自定义列数据展示
      checkFieldList.value = data.checkFieldList;
      filedColumns.value = data.filedColumns;
      // 渲染完成后同步自定义列的顺序到table的列上
      setTimeout(formatTbCol, 1000 / 60);
    } else {
      // 没有缓存，则请求最新的数据即可
      getConditionList();
    }
  }
);

// dataSource数据变化了，调用adjustTableHeight，重新计算maxHeight情况下的height值
watch(() => props.dataSource, adjustTableHeight, { deep: true });

onMounted(() => {
  window.addEventListener("scroll", handleCancelPopver, { passive: true });
  getConditionList();
  // props.enableColumnDrop && columnDrop();
  props.enableRowDrop && rowDrop();
  getLangRule();
  // 如果不需要触发提交,此功能必须keepSource和changeEditNeedTrigger为true时才有效
  if (props.changeEditNeedTrigger && props.keepSource) {
    document.addEventListener("click", bindEventToTriggerEditClose, true);
  }
  // 加入防抖优化
  window.addEventListener("resize", adjustTableHeight);
  hEmitter.on(cEmitterEvent.adjustTableHeight, adjustTableHeight);
  adjustTableHeight();
});
onBeforeUnmount(() => {
  document.removeEventListener("click", bindEventToTriggerEditClose, true);
  window.removeEventListener("resize", adjustTableHeight);
  hEmitter.off(cEmitterEvent.adjustTableHeight);
});
const onPropSelectChange = (value, data, c, row) => {
  if (value) {
    if (c.params.propSelectName) {
      row[c.params.propSelectName] = data[c.params.propsSelect.label];
    }
    if (c.params.propSelectAdd) {
      row[c.params.propSelectAdd] = data[c.params.propsSelect.keyAdd];
    }
    if (c.params.onPropSelectChange) {
      c.params.onPropSelectChange(value, c);
    }
  }
};
const onPropSelectClose = (c, row) => {
  row["countryCode"] = null;
  row["countryName"] = null;
  row["countryAdd"] = null;
  onCascaderClose(c);
};
const onCascaderChange = (options, value, c, row) => {
  const argeObj = getAreaInfoByCodesEnhanced(options, value);
  c.params.onCascaderChange && c.params.onCascaderChange(argeObj, row);
};
const onCascaderClose = (c, row) => {
  row["provinceName"] = null;
  row["provinceCode"] = null;
  row["cityName"] = null;
  row["cityCode"] = null;
  row["areaName"] = null;
  row["areaCode"] = null;
  row[c.prop] = [];
};
function getAreaInfoByCodesEnhanced(treeData, codeList) {
  if (
    !Array.isArray(treeData) ||
    !Array.isArray(codeList) ||
    codeList.length === 0
  ) {
    return {
      provinceName: "",
      provinceCode: codeList[0] || "",
      cityName: "",
      cityCode: codeList[1] || "",
      areaName: "",
      areaCode: codeList[2] || "",
    };
  }

  const result = {
    provinceName: "",
    provinceCode: codeList[0] || "",
    cityName: "",
    cityCode: codeList[1] || "",
    areaName: "",
    areaCode: codeList[2] || "",
  };

  // 递归查找函数
  const findNode = (nodes, targetCode, level) => {
    if (!nodes || !Array.isArray(nodes)) return null;

    for (const node of nodes) {
      if (node.areaCode === targetCode) {
        // 设置对应级别的名称
        if (level === 0) result.provinceName = node.areaName;
        if (level === 1) result.cityName = node.areaName;
        if (level === 2) result.areaName = node.areaName;

        return node;
      }
    }
    return null;
  };

  let currentNodes = treeData;

  // 逐级查找
  for (let i = 0; i < codeList.length; i++) {
    const code = codeList[i];
    const node = findNode(currentNodes, code, i);

    if (!node) break; // 如果某一级没找到，停止查找

    currentNodes = node.children; // 继续在子节点中查找下一级
  }

  return result;
}
const handleRemoteChange = (val, data, column, row, rowIndex) => {
  if (!val) return;
  if (column.params.multiple) {
    const arr = [];
    data.forEach((item) => {
      const obj = {};
      if (column.params.paramsKey) {
        for (const key in column.params.paramsKey) {
          obj[key] = data[column.params.paramsKey[key]];
        }
      }
      arr.push(obj);
    });
    row[column.params.prop] = arr;
  } else {
    if (column.params.paramsKey) {
      for (const key in column.params.paramsKey) {
        row[key] = data[column.params.paramsKey[key]];
      }
    }
  }
  column.params?.handleRemoteChange?.(data, rowIndex, row);
};
const onChange = (val, rowIndex, row, column) => {
  column.params?.change?.(val, rowIndex, row, column.params.options);
};
const onClear = (column, row) => {
  if (column?.params?.paramsKey || column?.params?.clearKey) {
    for (const key in column.params.paramsKey || column.params.clearKey) {
      row[key] = "";
    }
  }
  row[column.field] = "";
};
defineExpose({
  reloadTreeExpand,
  remove,
  setCheckboxRow,
  getCheckboxRecords,
  getCheckboxReserveRecords,
  getCheckboxIndeterminateRecords,
  clearCheckboxRow,
  editRowEvent,
  onClick,
  validEvent,
  setAllTreeExpand,
  reloadData,
  updateFooter,
  clearEdit,
  getInsertRecords,
  tableData: props.dataSource,
  tableId: props.tableId,
  sumDataObject,
  clearRadioRow,
  rowFullValidEvent,
});
</script>
<style lang="scss" scoped>
.select-content {
  max-height: 320px;
  padding-bottom: 40px;
  overflow-y: auto;

  &::-webkit-scrollbar {
    width: 4px;
  }

  &::-webkit-scrollbar-track {
    display: none;
  }

  &::-webkit-scrollbar-thumb {
    background-color: #888;
  }

  .select-content-tip {
    font-size: 12px;
    color: #a8abb2;
  }

  :deep() .el-divider--horizontal {
    margin: 17px 0;
  }

  footer {
    position: absolute;
    bottom: 16px;
    width: 240px;
    text-align: right;
  }
}

.config-line {
  display: flex;
  width: 130px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;

  .config-line-group {
    flex-shrink: 0;
    height: 20px;
    padding: 0 4px;
    margin-right: 8px;
    font-size: 12px;
    line-height: 20px;
    color: #333;
    background: #e2ebf7;
    border-radius: 4px;
  }

  .config-line-port {
    flex-shrink: 0;
    margin-right: 4px;
  }
}

.popover-div {
  display: flex;
  justify-content: right;
}

:deep() .vxe-toolbar.size--mini {
  position: absolute;
  top: -31px;
  right: 0;
  height: 28px;
}

/* // 触发虚拟滚动的样式 */
.vxe-table.size--small .vxe-body--column.col--ellipsis,
.vxe-table.size--small .vxe-footer--column.col--ellipsis,
.vxe-table.size--small .vxe-header--column.col--ellipsis,
.vxe-table.vxe-editable.size--small .vxe-body--column {
  height: 90px;
}

.table-status {
  i {
    display: inline-block;
    width: 6px;
    height: 6px;
    margin-top: -2px;
    margin-right: 5px;
    vertical-align: middle;
    border-radius: 100%;

    &.green {
      background-color: #4c9e4c;
    }

    &.blue {
      background-color: #3481e0;
    }

    &.red {
      background-color: red;
    }

    &.gray {
      background-color: #c5c4c4;
    }

    &.yellow {
      background-color: #f3a051;
    }
  }
}

.sortable-column .vxe-header--row .vxe-header--column.sortable-ghost,
.sortable-column .vxe-header--row .vxe-header--column.sortable-chosen {
  background-color: #dfecfb;
}

.sortable-column .vxe-header--row .vxe-header--column.col--fixed {
  cursor: no-drop;
}

// 这里统一通过css变量取修改vxe-table的基本样式
.sortable-column {
  // 修改vxe-table的行高
  --vxe-table-row-height-default: 44px;
  --vxe-table-row-height-medium: 40px;
  --vxe-table-row-height-small: 36px;
  --vxe-table-row-height-mini: 32px;
}

:deep() .vxe-header--column,
:deep() .vxe-footer--column {
  height: 40px !important;
  padding: 0 !important;
  line-height: 40px;
  color: #333;
  background-color: #ffffff !important;

  .vxe-cell--title {
    vertical-align: middle;
  }

  .vxe-cell {
    height: 100%;
  }

  .vxe-resizable.is--line::before {
    // height: 100%;
    height: 0;
  }
}

:deep() .filter-header-title {
  .el-icon {
    margin-right: 4px;
  }

  display: flex;
  align-items: center;
  line-height: 30px;
  //border-bottom: 1px solid #e8eaec;
}

:deep() .header-column-filter {
  .vxe-cell {
    max-height: inherit !important;
    padding-right: 0;
    padding-left: 0;
  }

  .vxe-cell--sort {
    position: absolute;
    top: 8px;
    right: 10px;
  }

  .filter-header-label {
    padding: 2px;
  }

  .el-input__inner {
    border-radius: 0;
  }
}

.pick-data-input {
  display: inline-block;
  width: 45%;
}

:deep() .vxe-table--body-wrapper,
:deep() .vxe-table--footer-wrapper {
  &::-webkit-scrollbar {
    width: 10px;
    height: 10px;
    background-color: transparent;
  }

  &::-webkit-scrollbar-thumb {
    background: #e8eaec;
  }
}

.line-upload-file {
  :deep() .el-button--mini {
    padding: 5px;
  }
}

:deep() .vxe-toolbar {
  top: 5px !important;
  right: 17px !important;
  z-index: 999;
  background-color: rgb(255 0 0 / 0%);
}

.first-col {
  position: relative;
  height: 20px;
}

.first-col::before {
  position: absolute;
  top: 10px;
  left: -15px;
  width: 170px;
  height: 1px;
  content: "";
  background-color: #e8eaec;
  transform: rotate(18deg);
}

.first-col .first-col-top {
  position: absolute;
  top: -10px;
  right: 4px;
}

.first-col .first-col-bottom {
  position: absolute;
  bottom: -10px;
  left: 4px;
}

// // 修复固定列高度不固定问题导致勾选框和序号消失
// :deep() .vxe-table--fixed-left-wrapper {
//   height: -webkit-fill-available !important;
// }

:deep() .vxe-table--header {
  background: #f5f5f5 !important;
}

:deep() .el-drawer__header {
  padding: 20px;
  margin-bottom: 0 !important;
  border-bottom: 1px solid #ededed;
}

:deep() .el-drawer__title {
  color: #333;
}

:deep() .el-drawer__body {
  padding-bottom: 60px;
}

.field-module {
  display: flex;
  flex-direction: column;
  row-gap: 4px;

  .drag-item {
    display: flex;
    align-items: center;
    height: 32px;

    .drag-item-handle {
      flex: none;
      margin-right: 10px;
      color: #b3b3b3;
      cursor: pointer;
    }

    .isFixed {
      display: flex;
      flex: 1;
      align-items: center;
      justify-content: center;
      height: 100%;
      font-size: 14px;
      color: #ffff;
      background-color: #eb5c20;
    }
  }

  :deep() .el-checkbox__input.is-checked + .el-checkbox__label {
    color: #666;
  }

  :deep() .el-checkbox__input.is-checked .el-checkbox__inner {
    background: #eb5c20;
    border-color: #eb5c20;
  }
}

.field-part {
  width: 100%;
  padding: 0 4px;
  margin: 2px 0;
  color: #666;
}

.btn {
  width: 24px;
  height: 20px;
  font-size: 12px;
  font-style: normal;
  font-weight: 400;
  line-height: 20px;
  color: #666;
  text-align: left;
  text-transform: none;

  .confirm {
    color: #eb5c20;
  }

  :hover {
    color: #eb5c20;
  }
}

.foot-btn {
  position: absolute;
  bottom: 0;
  left: 0;
  z-index: 1000;
  width: 100%;
  padding: 10px;
  background-color: #fff;
}

.setting-icon {
  position: absolute;
  top: 1px;
  right: 0;
  z-index: 99;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 38px;
  padding: 7px 10px;
  cursor: pointer;
  background: #ffffff;

  .text {
    margin-left: 3px;
    font-size: 13px;
    font-weight: 500;
    color: #333;
  }
}

.animate__animated {
  position: relative;
}

:deep() .vxe-header--column {
  .vxe-resizable {
    &:hover {
      cursor: col-resize;
    }

    &::after {
      display: inline-block;
      min-width: 2px;
      height: 30%;
      content: "";
      background: #dbdde1;
    }
  }

  &.col--fixed {
    .vxe-resizable {
      &::after {
        transform: translateX(-2px);
      }
    }
  }
}

:deep().vxe-cell--valid-error-hint {
  display: none;
}

:deep() {
  .el-date-editor.el-input {
    width: 100%;
  }

  .col--valid-error {
    &::before {
      border-color: transparent #f56c6c transparent transparent !important;
    }
  }
}

:deep().vxe-switch.is--on .vxe-switch--button {
  background: #67c23a !important;
}

:deep()
  .vxe-table--render-default
  .vxe-body--column
  .vxe-cell--valid-error-theme-beautify {
  display: none;
}

/* 状态样式 */
:deep() .status-type {
  height: 20px;
  padding: 0 8px;
  margin-top: -2px;
  font-size: 12px;
}
</style>
